package abg.core.service.chat.impl;

import abg.core.common.security.AuthUser;
import abg.core.common.security.AuthKit;
import abg.core.common.util.IdKit;
import abg.core.common.util.PinYinKit;
import abg.core.common.util.valid.Enum;
import abg.core.common.util.valid.Length;
import abg.core.common.util.valid.NotBlank;
import abg.core.common.util.valid.ValidKit;
import abg.core.common.util.valid.base.Valid;
import abg.core.domain.chat.ChatFriendVo;
import abg.core.domain.chat.ChatSearchFriendVo;
import abg.core.domain.chat.UserFriendListVo;
import abg.core.domain.db.ChatFriend;
import abg.core.domain.db.ChatFriendApply;
import abg.core.domain.db.SysUser;
import abg.core.domain.search.Psh;
import abg.core.domain.sys.MSG;
import abg.core.domain.sys.ServiceException;
import abg.core.mapper.ChatFriendApplyMapper;
import abg.core.mapper.ChatFriendMapper;
import abg.core.mapper.SysUserMapper;
import abg.core.service.chat.ChatFriendService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static abg.core.domain.db.table.ChatFriendApplyTableDef.CHAT_FRIEND_APPLY;
import static abg.core.domain.db.table.ChatFriendTableDef.CHAT_FRIEND;
import static abg.core.domain.db.table.SysUserTableDef.SYS_USER;

/**
 * @author leyili
 */
@Service
public class ChatFriendServiceImpl implements ChatFriendService {

    @Resource
    private ChatFriendMapper chatFriendMapper;

    @Resource
    private SysUserMapper userMapper;

    @Resource
    private ChatFriendApplyMapper chatFriendApplyMapper;


    //    @Override
    //    public List<UserFriendListVo> userGetFriendList(String userId) {
    //        //创建返回用数组
    //        List<UserFriendListVo> userFriendListVos = new ArrayList<>();
    //
    //        // 添加收藏数组
    //        UserFriendListVo collection = new UserFriendListVo();
    //        collection.setIndex("collection");
    //        userFriendListVos.add(collection);
    //
    //        //添加26个大写字母数组
    //        char charCodeOfA = 'A';
    //        for (int i = 0; i < 27; i++) {
    //            UserFriendListVo e = new UserFriendListVo();
    //            e.setIndex(String.valueOf((char) (charCodeOfA + i)));
    //            userFriendListVos.add(e);
    //        }
    //        // 添加其他数组
    //        UserFriendListVo other = new UserFriendListVo();
    //        other.setIndex("other");
    //        userFriendListVos.add(other);
    //
    //
    //        for (UserFriendListVo item : userFriendListVos) {
    //            QueryWrapper wrapper = QueryWrapper.create().select(CHAT_FRIEND.ALL_COLUMNS)
    //                    .from(ChatFriend.class)
    //                    .leftJoin(SysUser.class)
    //                    .on(CHAT_FRIEND.FRIEND_ID.eq(SYS_USER.ID))
    //                    .select(SYS_USER.NICK_NAME, SYS_USER.AVATAR)
    //                    .and(CHAT_FRIEND.USER_ID.eq(userId))
    //                    .and(CHAT_FRIEND.TYPE.eq(item.getIndex()))
    //                    // 根据昵称排序
    //                    .orderBy(CHAT_FRIEND.REMARK_NAME.desc());
    //            item.setList(chatFriendMapper.selectListByQueryAs(wrapper, ChatFriendVo.class));
    //        }
    //        return userFriendListVos;
    //    }

    //用户查询自己的朋友列表
    @Override
    public List<UserFriendListVo> userGetFriendList(String userId) {
        //所有Type
        ArrayList<String> typeList = new ArrayList<>(28);
        typeList.add("collection");
        char charCodeOfA = 'A';
        for (int i = 0; i < 26; i++) {
            typeList.add(String.valueOf((char) (charCodeOfA + i)));
        }
        typeList.add("other");

        //填充数据
        ArrayList<UserFriendListVo> userFriendListVos = new ArrayList<>();
        for (String type : typeList) {
            QueryWrapper wrapper = QueryWrapper.create()
                    .select(CHAT_FRIEND.ALL_COLUMNS, SYS_USER.NICK_NAME, SYS_USER.AVATAR)
                    .leftJoin(SysUser.class)
                    .on(CHAT_FRIEND.FRIEND_ID.eq(SYS_USER.ID))
                    .and(CHAT_FRIEND.USER_ID.eq(userId))
                    .and(CHAT_FRIEND.TYPE.eq(type))
                    //根据昵称默认排序
                    .orderBy(CHAT_FRIEND.REMARK_NAME.asc());
            List<ChatFriendVo> chatFriendVos = chatFriendMapper.selectListByQueryAs(wrapper, ChatFriendVo.class);

            //组装数据
            UserFriendListVo userFriendListVo = new UserFriendListVo();
            userFriendListVo.setIndex(type);
            userFriendListVo.setList(chatFriendVos);
            userFriendListVos.add(userFriendListVo);
        }

        return userFriendListVos;
    }

    @Valid
    @Override
    public ChatSearchFriendVo searchFriend(@Length(mast = 11, msg = "请正确输入对方手机号") String userPhone) {
        AuthKit.mastLogin();

        QueryWrapper queryWrapper = QueryWrapper.create().eq("phone", userPhone).limit(1);
        SysUser sysUser = userMapper.selectOneByQuery(queryWrapper);

        if (sysUser != null) {
            String nickName = sysUser.getNickName();
            String userId = sysUser.getId();
            ChatSearchFriendVo chatSearchFriendVo = new ChatSearchFriendVo();
            chatSearchFriendVo.setUserId(userId);
            chatSearchFriendVo.setNickName(nickName);
            chatSearchFriendVo.setAvatar(sysUser.getAvatar());
            chatSearchFriendVo.setPhone(userPhone);
            return chatSearchFriendVo;
        }
        return null;
    }


    //申请添加好友分页数据
    @Override
    public Page<ChatFriendApply> applyFriendPageData(@Length(mast = 11, msg = "请正确输入对方手机号") String userPhone, Psh psh) {
        AuthUser authUser = AuthKit.mastLogin();
        String currentUserId = authUser.getUserId();
        QueryWrapper wrapper = QueryWrapper.create()
                .select(CHAT_FRIEND_APPLY.ALL_COLUMNS, SYS_USER.NICK_NAME.as("applyUserName"), SYS_USER.AVATAR.as("applyUserAvatar"))
                .leftJoin(SYS_USER).on(SYS_USER.ID.eq(CHAT_FRIEND_APPLY.FRIEND_USER_ID))
                .and(CHAT_FRIEND_APPLY.FRIEND_USER_ID.eq(currentUserId))
                .and(CHAT_FRIEND_APPLY.APPLY_STATUS.eq("0"))
                .and(SYS_USER.PHONE.eq(userPhone))
                .orderBy(CHAT_FRIEND_APPLY.APPLY_TIME.desc());

        return chatFriendApplyMapper.paginate(psh, wrapper);
    }

    //申请添加好友
    @Valid
    @Override
    public boolean applyFriend(@NotBlank String friendUserId, String remark) {
        AuthUser authUser = AuthKit.mastLogin();
        //不能添加自己
        if (authUser.getUserId().equals(friendUserId))
            throw new ServiceException(MSG.CHAT_APPLY_DONT_MY);

        //好友申请已经通过
        ChatFriend byId = chatFriendMapper.getById(authUser.getUserId(), friendUserId);
        if (byId != null) throw new ServiceException(MSG.CHAT_APPLY_ACCESS);

        //已发起申请
        ChatFriendApply chatFriendApply = chatFriendApplyMapper.selectOneByQuery(
                QueryWrapper.create()
                        .eq("apply_user_id", authUser.getUserId())
                        .eq("friend_user_id", friendUserId)
                        .eq("apply_status", "0")
        );
        if (chatFriendApply != null) return true;

        ChatFriendApply apply = new ChatFriendApply();
        apply.setId(IdKit.getId());
        apply.setApplyRemark(remark);
        apply.setApplyUserId(authUser.getUserId());
        apply.setFriendUserId(friendUserId);
        apply.setApplyTime(LocalDateTime.now());
        chatFriendApplyMapper.insertSelective(apply);

        return true;
    }

    //处理好友申请
    @Valid
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean processFriendApply(@NotBlank String applyId, @Enum({"1", "2"}) String status, String remark) {
        ChatFriendApply apply = chatFriendApplyMapper.selectOneById(applyId);
        if (apply == null || !apply.getApplyStatus().equals("0")) throw new ServiceException(MSG.CHAT_APPLY_LAPSE);
        apply.setApplyStatus(status);
        apply.setProcessRemark(remark);
        apply.setProcessTime(LocalDateTime.now());
        chatFriendApplyMapper.update(apply);

        //添加好友关系
        if ("1".equals(status)) {
            //
            ChatFriend chatFriend = new ChatFriend();
            chatFriend.setUserId(apply.getApplyUserId());
            chatFriend.setFriendId(apply.getFriendUserId());

            String nickName = userMapper.getNickName(apply.getFriendUserId());
            chatFriend.setRemarkName(nickName);

            boolean isChinese = ValidKit.chineseText.check(nickName.substring(0, 1));
            if (isChinese) {
                String ontFirst = PinYinKit.getOntFirst(nickName);
                chatFriend.setType(ontFirst);
            } else {
                chatFriend.setType("other");
            }
            chatFriendMapper.insertSelective(chatFriend);

            chatFriend = new ChatFriend();
            chatFriend.setUserId(apply.getFriendUserId());
            chatFriend.setFriendId(apply.getApplyUserId());

            //
            nickName = userMapper.getNickName(apply.getApplyUserId());
            chatFriend.setRemarkName(nickName);

            isChinese = ValidKit.chineseText.check(nickName.substring(0, 1));
            if (isChinese) {
                String ontFirst = PinYinKit.getOntFirst(nickName);
                chatFriend.setType(ontFirst);
            } else {
                chatFriend.setType("other");
            }
            chatFriendMapper.insertSelective(chatFriend);

        }

        return true;
    }

    //双向删除好友
    @Valid
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delFriend(@NotBlank String friendUserId) {
        AuthUser authUser = AuthKit.mastLogin();
        String currentUserId = authUser.getUserId();

        //双向删除好友
        chatFriendMapper.delById(currentUserId, friendUserId);

        chatFriendMapper.delById(friendUserId, currentUserId);

        return false;
    }

    @Valid
    @Override
    public List<ChatSearchFriendVo> searchFriendList(@NotBlank(msg = "请输入搜索内容") String searchKey) {
        AuthUser authUser = AuthKit.mastLogin();
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(SYS_USER.ALL_COLUMNS)
                .from(CHAT_FRIEND)
                .leftJoin(SYS_USER).on(CHAT_FRIEND.FRIEND_ID.eq(SYS_USER.ID))
                .and(CHAT_FRIEND.USER_ID.eq(authUser.getUserId()))
                .and(SYS_USER.PHONE.like(searchKey).or(SYS_USER.NICK_NAME.like(searchKey)))
                .limit(50);

        return userMapper.selectListByQueryAs(queryWrapper, ChatSearchFriendVo.class);
    }

    @Override
    public SysUser getFriendInfo(String friendId) {
        AuthUser authUser = AuthKit.mastLogin();
        SysUser sysUser = userMapper.selectOneById(friendId);
        sysUser.setPassword(null);
        sysUser.setPhone(null);
        return sysUser;
    }

}
